﻿using Application.Commons.Data;
using FrameworkCore.Constants;
using FrameworkCore.Extensions;
using FrameworkCore.Helpers;
using FrameworkCore.Models;
using MediatR;
using Microsoft.Extensions.Configuration;
using System.ComponentModel.DataAnnotations;

namespace NM.Module.Manager.API.Commands.Delete;

#nullable disable

/// <summary>
/// 删除模块
/// </summary>
public class DeleteModulerCommand : IRequest<Result<bool>>
{
    /// <summary>
    /// 模块库主键
    /// </summary>
    [Required(ErrorMessage = "模块库主键必传")]
    public long ModulerLibraryId { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class DeleteModulerCommandHandler : IRequestHandler<DeleteModulerCommand, Result<bool>>
{
    private readonly ApplicationDbContext _context;
    public DeleteModulerCommandHandler(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Result<bool>> Handle(DeleteModulerCommand request, CancellationToken cancellationToken)
    {
        var modulerLibrary = await _context.ModulerLibraries.FindAsync(request.ModulerLibraryId);
        ExceptionHelper.ThrowIfNull(modulerLibrary, "数据不存在");

        var uploadPath = ApplicationPartManagerExtensions
            .GetModulesDirectory(ConfigurationsExtensions.GetGlobalSection<List<string>>(GlobalConstants.UploadPathsKey));

        string deleteModulerPath = Path.Combine(uploadPath, modulerLibrary.Name);

        _context.ModulerLibraries.Remove(modulerLibrary);
        var count = await _context.SaveChangesAsync(cancellationToken);
        if (count > 0 && File.Exists(deleteModulerPath))
        {
            File.Delete(deleteModulerPath);
        }
        ExceptionHelper.ThrowIfTrue(count == 0, "删除失败");

        return await Result<bool>.SucceedAsync(true);
    }
}